#ifndef _TOOLS_H
#define _TOOLS_H

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <stdarg.h>

// 获取文件大小（以字节计）
long getFileSize(FILE *fp) {
    if (fp == NULL) return -1; // 错误处理
    long fsize;
    fseek(fp, 0, SEEK_END);
    fsize = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    return fsize;
}

// 文件复制函数
long fcopy(FILE *fSource, long offsetSource, long len, FILE *fTarget, long offsetTarget) {
    if (fSource == NULL || fTarget == NULL) return -1; // 错误处理

    fseek(fSource, offsetSource, SEEK_SET);
    fseek(fTarget, offsetTarget, SEEK_SET);
    
    char *buffer = (char *)malloc(len);
    if (buffer == NULL) return -1; // 内存分配失败

    size_t bytesRead = fread(buffer, 1, len, fSource);
    size_t bytesWritten = fwrite(buffer, 1, bytesRead, fTarget);

    free(buffer);
    return bytesWritten; // 返回复制的字节数
}

// 向文件中插入内容
int finsert(FILE *fp, long offset, void *buffer, int len) {
    if (fp == NULL || buffer == NULL || len <= 0) return -1; // 错误处理
    
    long fileSize = getFileSize(fp);
    if (fileSize < 0) return -1;

    fseek(fp, offset, SEEK_SET);
    
    char *originalData = (char *)malloc(fileSize - offset);
    if (originalData == NULL) return -1; // 内存分配失败

    fread(originalData, 1, fileSize - offset, fp);
    fseek(fp, offset, SEEK_SET);
    fwrite(buffer, 1, len, fp);
    fwrite(originalData, 1, fileSize - offset, fp);

    free(originalData);
    return 0; // 成功
}

// 从文件中删除内容
int fdelete(FILE *fp, long offset, int len) {
    if (fp == NULL || len <= 0) return -1; // 错误处理

    long fileSize = getFileSize(fp);
    if (fileSize < 0) return -1;

    fseek(fp, offset + len, SEEK_SET);
    char *remainingData = (char *)malloc(fileSize - offset - len);
    if (remainingData == NULL) return -1; // 内存分配失败

    fread(remainingData, 1, fileSize - offset - len, fp);
    fseek(fp, offset, SEEK_SET);
    fwrite(remainingData, 1, fileSize - offset - len, fp);
    _chsize(_fileno(fp), fileSize - len);

    free(remainingData);
    return 0; // 成功
}

// 暂停程序
void pause(const char *str, ...) {
    va_list vl;
    char buf[500] = {0};
    va_start(vl, str);
    vsnprintf(buf, sizeof(buf), str, vl);
    va_end(vl);
    printf("%s", buf);
    getch();
    printf("\n");
}

#endif // _TOOLS_H
